#include <iostream>
#include <string>
#include <thread>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "netaddr.hpp"
using namespace std;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Incorrect use, correct use :" << endl
             << "        ./server local_ip local_port" << endl;
        return 1;
    }
    // 初始化服务端套接字
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    // 网络文件信息
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    // 绑定套接字，不需要显式的bind，会在第一次发消息时bind随机端口号

    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_addr.s_addr = inet_addr(ip.c_str());
    serveraddr.sin_port = htons(port);
    serveraddr.sin_family = AF_INET;

    thread Write([sockfd, serveraddr]()
                 {
        netaddr addr(serveraddr);
        while(true)
        {
            string msg;
            getline(cin, msg);
            sendto(sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr*)&addr.GetAddr(), sizeof(addr.GetAddr()));
        } });

    thread Read([sockfd]()
                {
        char buffer[1024];
        while(true)
        {
            struct sockaddr_in addr;
            socklen_t len = sizeof(addr);
            int n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&addr, &len);
            if(n > 0)
            {
                netaddr serveraddr(addr);
                cerr << serveraddr.SockInfo() << "# " << buffer << endl;
            }
            else
            {
                cout << "read err" <<endl;
                break;
            }
        } });

    Write.join();
    Read.join();

    close(sockfd);
    return 0;
}
